import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/item/item_game.dart';
import 'package:test2/model/game.dart';
import 'package:test2/util/bus.dart';
import 'package:test2/view/game_add.dart';
import 'package:test2/view/map_list.dart';

class GameList extends StatefulWidget {
  const GameList({super.key});

  @override
  State<GameList> createState() => _GameListState();
}

class _GameListState extends BaseState<GameList> {
  late Box<Game> box;
  List<Game> dataList = [];

  @override
  void initState() {
    init();
    bus.on(EventType.game, onGameChange);
    super.initState();
  }

  onGameChange(arg) {
    updateList();
  }

  @override
  void dispose() {
    bus.off(EventType.game, onGameChange);
    super.dispose();
  }

  void init() async {
    box = await Hive.openBox<Game>("game");
    updateList();
  }

  void updateList() {
    setState(() {
      dataList.clear();
      dataList.addAll(box.values);
      dataList = dataList.reversed.toList();

      // 置顶
      final topGames = dataList.where((game) => game.top).toList();
      final normalGames = dataList.where((game) => !game.top).toList();

      dataList = [...topGames, ...normalGames];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("游戏库")),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          addGame();
        },
        child: Icon(Icons.add),
      ),
      body: SizedBox.expand(
        child: Column(
          children: [
            Expanded(
              child: ListView.separated(
                padding: EdgeInsets.only(
                  left: 16,
                  right: 16,
                  top: 16,
                  bottom: 100,
                ),
                itemBuilder: (context, index) {
                  var item = dataList[index];
                  return GestureDetector(
                    onTap: () {
                      itemClick(item);
                    },
                    child: ItemGame(game: item),
                  );
                },
                separatorBuilder: (context, index) {
                  return SizedBox(height: 12);
                },
                itemCount: dataList.length,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void itemClick(Game game) {
    startPage(MapList(boxName: "game${game.key}", gameName: game.name));
  }

  void addGame() {
    startPage(GameAdd());
  }
}
